package com.ruitu.mall_98_1.product.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.BaseFragment;
import com.beanu.arad.utils.ToastUtils;
import com.ruitu.mall_98_1.R;
import com.ruitu.mall_98_1.dao.api.APIRetrofit;
import com.ruitu.router_module.A_Rutils;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.product.Category;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/09/12.
 */
public class CategoryFragment extends BaseFragment {
    private LinearLayout ll_menu, ll_search;//左侧的以及菜单,搜索
    //    private TextView tv_title;//标题
    private RelativeLayout rl_content, rl_reload;//内容页面,重新加载数据的布局
    private TextView tv_reload;//重新加载数据的按钮

    private List<Category> categoryList = new ArrayList<>();

    public static CategoryFragment newInstance() {
        Bundle args = new Bundle();
        CategoryFragment fragment = new CategoryFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(EventModel e) {
        if (e.getEventCode() == 19012252) {//请求分类数据
            reqCategory();//请求分类的数据
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Arad.bus.register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_category, container, false);
        ll_menu = v.findViewById(R.id.ll_menu);
        rl_content = v.findViewById(R.id.rl_content);
        rl_reload = v.findViewById(R.id.rl_reload);
        tv_reload = v.findViewById(R.id.tv_reload);
        ll_search = v.findViewById(R.id.ll_search);

        setListeners();
        return v;
    }

    private void setListeners() {
        tv_reload.setOnClickListener(this);
        ll_search.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v == tv_reload) {//请求数据失败等原因时,重新加载数据
            reqCategory();
        }
        if (v == ll_search) {//搜索
            try {
                A_Rutils.startActivity(getActivity(), "com.ruitu.mall_98_1.search.SearchActivity");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showContent(boolean isShow) {//是否显示分类数据
        if (isShow) {
            rl_content.setVisibility(View.VISIBLE);
            rl_reload.setVisibility(View.GONE);
        } else {
            rl_content.setVisibility(View.GONE);
            rl_reload.setVisibility(View.VISIBLE);
        }
    }

    private void setState(int index) {
        for (int i = 0; i < ll_menu.getChildCount(); i++) {
            if (i == index) {
                ll_menu.getChildAt(i).setSelected(true);
            } else {
                ll_menu.getChildAt(i).setSelected(false);
            }
        }
    }

    private void setData() {
        ll_menu.removeAllViews();
        for (int i = 0; i < categoryList.size(); i++) {
            View v = View.inflate(getActivity(), R.layout.pro_category_item_layout, null);
            TextView tv_name = v.findViewById(R.id.tv_name);
            tv_name.setText(categoryList.get(i).getTypeName());
            tv_name.setTag(categoryList.get(i));
            if (i == 0) {
                v.setSelected(true);
                FragmentTransaction ft = getChildFragmentManager().beginTransaction();
                ft.replace(R.id.container, CategoryDetailFragment.newInstance(categoryList.get(i)), "category").commit();
            }
            tv_name.setOnClickListener(new OnMenuClickListener());
            ll_menu.addView(v);
        }
    }

    private class OnMenuClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Category category = (Category) v.getTag();
            for (int i = 0; i < categoryList.size(); i++) {
                if (category == categoryList.get(i)) {
                    setState(i);
                    break;
                }
            }
            FragmentTransaction ft = getChildFragmentManager().beginTransaction();
            ft.replace(R.id.container, CategoryDetailFragment.newInstance(category), "category").commit();
        }
    }

    private void reqCategory() {//请求三级分类列表
        APIRetrofit.getDefault().reqCategory(AppHolder.instance().getCITY().getName())
                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult<List<Category>>>() {
                    @Override
                    public void onError(Throwable e) {
                        showProgress(false);
                        showContent(false);
                    }

                    @Override
                    public void onNext(BaseResult<List<Category>> listResult) {
                        showProgress(false);
                        if (listResult.isSuccess()) {
                            List<Category> newData = listResult.getData();
                            if (!isDataEmpty(newData)) {
                                categoryList.clear();
                                categoryList.addAll(newData);
                                setData();
                                showContent(true);
                            } else {
                                showContent(false);
                            }
                        } else {
                            ToastUtils.showShortSafe(listResult.getMsg());
                            showContent(false);
                        }
                    }
                });
    }
}
